package com.dc.web.controller;


import com.dc.config.CommonConfig;
import com.dc.config.ServerConfig;
import com.dc.constant.MessageConstant;
import com.dc.dao.ShipDao;
import com.dc.dao.ShipRepairDao;
import com.dc.entity.ShipEntity;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.ShipListSearchBody;
import com.dc.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/api/ship")
@Slf4j
public class ShipController {

    @Resource
    ShipDao shipDao;

    @Resource
    ServerConfig serverConfig;

    @Resource
    private ShipRepairDao shipRepairDao;


    @GetMapping("/dict")
    public AjaxResult dict(@RequestParam(name = "type", required = false) String type) {

        List<ShipEntity> list = null;

        if(ObjectUtils.isEmpty(type)) {
             list = shipDao.findAll();
        } else {
            list = shipDao.findShipListByType(type);
        }

        List<Map<String, Object>> result = new ArrayList<>();

        if(ObjectUtils.isEmpty(list)) {
            return AjaxResult.success(result);
        }

        for(ShipEntity shipEntity : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("label", shipEntity.getName());
            map.put("value", shipEntity.getId());
            boolean exists = shipRepairDao.existsByShipId(shipEntity.getId());
            map.put("hasOrder", exists);

            result.add(map);
        }

        return AjaxResult.success(result);
    }


    /**
     * 根据 船类型和名称 来展示船列表
     * @param
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(ShipListSearchBody shipListSearchBody) {

        Integer pageNumber = shipListSearchBody.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = shipListSearchBody.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        String name = shipListSearchBody.getName();
        String type = shipListSearchBody.getType();

        Page<ShipEntity> shipEntities = null;

        if(ObjectUtils.isEmpty(name) && ObjectUtils.isEmpty(type)) {
            shipEntities = shipDao.findAll(pageRequest);
        } else if(ObjectUtils.isEmpty(name)) {
            shipEntities = shipDao.findShipEntitiesByType(type, pageRequest);
        } else if(ObjectUtils.isEmpty(type)) {
            shipEntities = shipDao.findShipEntitiesByName(name, pageRequest);
        } else {
            shipEntities = shipDao.findShipEntitiesByTypeAndName(type, name, pageRequest);
        }
        return AjaxResult.success(shipEntities);
    }

    /**
     * 展示船基础信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {
        Optional<ShipEntity> shipEntityOptional = shipDao.findById(id);
        if (shipEntityOptional.isPresent()) {
            ShipEntity shipEntity = shipEntityOptional.get();
            return AjaxResult.success(shipEntity);
        } else {
            return AjaxResult.error("id 为 " + id + " 的船基础信息不存在!");
        }
    }

    /**
     * 新增船信息
     * @param pic
     * @param name
     * @param type
     * @return
     * @throws Exception
     */
    @PostMapping()
    public AjaxResult add(@RequestParam(name = "pic", required = false) MultipartFile pic,
                         @RequestParam("name") String name,
                         @RequestParam("type") String type) {
        try {
            String shipPicPath = null;
            if(pic != null && !pic.isEmpty()) {
                shipPicPath = FileUploadUtils.upload(CommonConfig.getShipPicPath(), pic, MimeTypeUtils.IMAGE_EXTENSION);
            }
            ShipEntity shipEntity = new ShipEntity();
            shipEntity.setPic(shipPicPath);
            shipEntity.setName(name);
            shipEntity.setType(type);

            shipDao.save(shipEntity);
            return AjaxResult.success(shipEntity);
        } catch (Exception e) {
            return AjaxResult.error(MessageConstant.ERR_UPLOAD_SHIP_PIC);
        }
    }

    /**
     * 更新船基础信息
     * @param id
     * @param pic
     * @param name
     * @param type
     * @return
     */
    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id,
                             @RequestParam(name = "pic", required = false) MultipartFile pic,
                             @RequestParam(name = "name") String name,
                             @RequestParam(name = "type") String type) {

        try {
            String shipPicPath = null;
            if(pic != null && !pic.isEmpty()) {
                shipPicPath = FileUploadUtils.upload(CommonConfig.getShipPicPath(), pic, MimeTypeUtils.IMAGE_EXTENSION);
            }
            ShipEntity shipEntity = new ShipEntity();
            shipEntity.setId(id);
            shipEntity.setPic(shipPicPath);
            shipEntity.setName(name);
            shipEntity.setType(type);

            shipDao.save(shipEntity);
            return AjaxResult.success(shipEntity);
        } catch (Exception e) {
            return AjaxResult.error(MessageConstant.ERR_UPLOAD_SHIP_PIC);
        }
    }

    /**
     * 删除船基础信息
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        boolean exists = shipRepairDao.existsByShipId(id);
        if(exists) {
            throw new ServiceException(MessageConstant.ERR_SHIP_EXIST_REPAIR);
        }

        shipDao.deleteById(id);

        return AjaxResult.success();
    }

//    /**
//     * 上传船的图片并且返回路径
//     * @param file
//     * @return
//     * @throws Exception
//     */
//    private void uploadFile(MultipartFile file) throws Exception {
//
//        if (!file.isEmpty()) {
//            String shipPicPath = FileUploadUtils.upload(CommonConfig.getShipPicPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
//            String url = serverConfig.getUrl() + shipPicPath;
//            AjaxResult ajax = AjaxResult.success();
//            Map<String, Object> result = new HashMap<>();
//            result.put("url", url);
//            result.put("fileName", shipPicPath);
//            result.put("newFileName", FileUtils.getName(shipPicPath));
//            result.put("originalFilename", file.getOriginalFilename());
//        }
//    }
}
